import React, {Component, createRef} from 'react';
import axios from "axios";
import './index.css'

class AxiosDemo extends Component {

    inputCityRef = createRef();

    state = {
        list: [],
        weather: {}
    }

    componentDidMount() {
        this.getCityWeather()
    }

    render() {
        return (
            <div>
                {/*加载每日分享的精美语句*/}
                <button onClick={this.getRecommend}>加载每日分享的精美语句</button>
                <ul>
                    {
                        this.state.list.map((item, index) =>
                            <li key={index}>{item.content}</li>
                        )
                    }

                </ul>

                {/*天气查询*/}
                <div className="weather">
                    <h2>天气查询</h2>
                    <input placeholder={'请输入要查询的城市'} ref={this.inputCityRef} defaultValue={"昆明"}/>
                    <button onClick={this.getCityWeather}>查询</button>
                    <div>
                        <p><strong>城市名称：</strong> <span>{this.state.weather.address}</span></p>
                        <p><strong>更新日期：</strong> <span>{this.state.weather.reportTime}</span></p>
                        <p><strong>城市温度：</strong> <span>{this.state.weather.temp}</span></p>
                        <p><strong>天气描述：</strong> <span>{this.state.weather.weather}</span></p>
                        <p><strong>城市湿度：</strong> <span>{this.state.weather.humidity}</span></p>
                    </div>
                </div>
            </div>
        );
    }

    // 每日分享的精美语句
    getRecommend = () => {
        axios.get("/mxnzp-api/daily_word/recommend", {
            params: {
                count: 10,
                app_id: 'gctfrffdsrsnalyi',
                app_secret: 'OW13ano4b0w3UExtK21mMGZyRTVXQT09',
            }
        }).then((res) => {
            // this.setState({
            //     list: res.data.data
            // })

            // 设置完成的回调
            // this.setState({list: res.data.data}, () => {
            //     console.log("设置的list=", this.state.list);
            // })

            // 函数式
            this.setState((state, props) => {
                return {
                    list: res.data.data
                }
            })
        })
    }

    // 天气查询
    getCityWeather = () => {
        // 获取输入的城市名称
        const inputCity = this.inputCityRef.current.value;
        axios.get(`/mxnzp-api/weather/current/${inputCity}`, {
            params: {
                app_id: 'gctfrffdsrsnalyi',
                app_secret: 'OW13ano4b0w3UExtK21mMGZyRTVXQT09',
            }
        }).then((res) => {
            this.setState({
                weather: res.data.data
            })
        })
    }
}

export default AxiosDemo;
